package StudyCode.summary.mycollection;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReturnsTheGivenIteratorNElement {
	public static <T> T fromEnd(Iterator<T> iterator, int n) {
		return assertNotNull(iterator, fromEndOrNull(iterator, n));
	}


	public static <T> T fromEnd(Iterable<T> iterable, int n) {
		return fromEnd(iterable.iterator(), n);
	}

	private static <T> T assertNotNull(Iterator<T> iterator, T result) {

		return result;
	}

	public static <T> T fromEndOrNull(Iterator<T> iterator, int n) {
		Deque<T> trail = new ArrayDeque<T>(n);
		while (iterator.hasNext()) {
			if (trail.size() > n) {
				trail.removeLast();
			}
			trail.addFirst(iterator.next());
		}
		return trail.size() == n + 1 ? trail.getLast() : null;
	}


	public static <T> T fromEndOrNull(Iterable<T> iterable, int countFromEnd) {
		return fromEndOrNull(iterable.iterator(), countFromEnd);
	}
}
